/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ani.h"
#include <iostream>
#include <cstring>
#include <cassert>
#include <vector>
#include "libarkbase/utils/logger.h"

ani_ref checkReturnNull(ani_env *env) {
    ani_ref ref = nullptr;
    LOG_IF(env->GetNull(&ref) != ANI_OK, FATAL, ANI) << "Failed to get null reference";
    return ref;
}

ani_ref checkReturnUndefined(ani_env *env) {
    ani_ref ref = nullptr;
    LOG_IF(env->GetUndefined(&ref) != ANI_OK, FATAL, ANI) << "Failed to get undefined reference";
    return ref;
}

const std::vector<ani_native_function> methods = {
    {"checkReturnNull", nullptr, reinterpret_cast<void *>(checkReturnNull)},
    {"quickCheckReturnNull", nullptr, reinterpret_cast<void *>(checkReturnNull)},
    {"checkReturnUndefined", nullptr, reinterpret_cast<void *>(checkReturnUndefined)},
    {"quickCheckReturnUndefined", nullptr, reinterpret_cast<void *>(checkReturnUndefined)},
};

ANI_EXPORT ani_status ANI_Constructor(ani_vm *vm, uint32_t *result)
{
    ani_env *env;
    LOG_IF(vm->GetEnv(ANI_VERSION_1, &env) != ANI_OK, FATAL, ANI) << "Unsupported ANI_VERSION_1";

    static const char *moduleName = "EtsAniTests";

    ani_module module;

    LOG_IF(env->FindModule(moduleName, &module) != ANI_OK, FATAL, ANI) << "Not found '" << moduleName << "'";

    for (auto &m : methods) {
        LOG_IF(env->Module_BindNativeFunctions(module, &m, 1) != ANI_OK, FATAL, ANI) << "Failed to bind function'" << m.name << "'";
    }
    *result = ANI_VERSION_1;
    return ANI_OK;
}
